package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password){
        try {
            //获取subject主体
            Subject subject = SecurityUtils.getSubject();

            //方式一：在封装token之前就直接对密码进行加密，再传给shiro直接对比相同
            //对密码进行加密
           // Md5Hash md5Hash = new Md5Hash(password,username,2);
            //把前端传过来的参数封装为令牌
            //UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toString());
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);

            //方式二：登录时不需要自己加密，告诉shiro登录时要做加密，并且告诉shiro算法是怎么样的

            //使用shiro提供的api来登录（必须要使用该方法，才会改变subject的认证状态）
            subject.login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult(false,"用户名不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false,"密码错误");
        } catch (DisabledAccountException e) {
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }

}
